// pages/my/myAppeal/myAppeal.js
import {
  pageAppeal,
  appealToEndorse,
  appealToCancel
} from "../../../api/index"
import {
  timeFormat
} from "../../../utils/util"
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    CustomBar: app.globalData.CustomBar,
    appealList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getAppeal()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  goToDetail: function (e) {
    let id = e.currentTarget.dataset.id

    wx.navigateTo({
      url: '/pages/appealDetails/appealDetails?appealId=' + id
    })
  },
  appealEndorse: async function (e) {
    //点赞
    const id = e.currentTarget.dataset.item._id
    const index = e.currentTarget.dataset.index
    const isEndorse = this.data.appealList[index].isEndorse
    const endorseCount = this.data.appealList[index].endorseCount
    let result = null
    if (isEndorse) {
      result = await appealToCancel({
        appealId: id
      })
    } else {
      result = await appealToEndorse({
        appealId: id
      })
    }

    console.log(result)
    if (result) {
      console.log(12132)
      this.setData({
        [`appealList[${index}].isEndorse`]: !isEndorse,
        [`appealList[${index}].endorseCount`]: isEndorse ? endorseCount - 1 : endorseCount + 1
      })
    }
  },
  getAppeal: async function () {
    let userInfo = wx.getStorageSync('wjUser')
    let params = {
      openid: userInfo._openid,
      pageNO: 1,
      pageSize: 10
    }
    const result = await pageAppeal(params)
    if (result) {
      console.log(result)
      for (let i in result) {
        result[i].createTime = timeFormat(result[i].createTime)
      }
      this.setData({
        appealList: result
      })
    }
  }
})